<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        div {
            position: absolute;
            width: 100px;
            height: 100px;
            background-color: pink;
        }
        
        #box2 {
            position: absolute;
            width: 100px;
            height: 100px;
            background-color: purple;
            left: 100px;
            top: 200px;
        }
    </style>
    <script>
        window.onload = function() {
            var box = document.getElementById('box');

            box.onmousedown = function(event) {
                // ie支持
                if (box.setCapture) {
                    box.setCapture();
                }
                event = event || window.event;
                var ol = event.clientX - box.offsetLeft;
                var ot = event.clientY - box.offsetTop;
                document.onmouseover = function(event) {
                    event = event || window.event;
                    var x = event.clientX;
                    var y = event.clientY;
                    box.style.top = (y - ot) + 'px';
                    box.style.left = (x - ol) + 'px';
                }
                document.onmouseup = function() {
                        document.onmouseover = null;
                        document.onmouseup = null;
                        if (box.releaseCapture) {
                            box.releaseCapture();
                        }
                    }
                    // 取消拖拽的默认行为
                return false;
            }

        }
    </script>
</head>

<body>
    <div id='box'></div>
    <div id='box2'></div>
</body>

</html>